import React, { useMemo, useState } from "react";
import { history, useModel } from "@umijs/max";
import { Button, DatePicker, Form, Input, Modal, Space, Table, message } from "antd";
import XlSelect from "@/components/Form/XlSelect";
import { ArrowDownOutlined, PlusOutlined } from "@ant-design/icons";
import type { ColumnsType } from 'antd/es/table';
import { orderTypes } from "@/constants/types";
import XlCheckBox from "@/components/Form/XlCheckBox";
import { orderStatusMaps  } from "@/constants/dictData";
import { calculateTableWidth, downloadFile } from "@/utils/util";
import { fetchOrderList, fetchOrderTabNum, orderExportMt, orderImportTracks, orderImportEntrust, orderCancel, exportInWhDataSingle, confirmOrderInWhVerifyData, importReceiptData, orderUpdateReceiptOrder } from '../services';
import { useComponentDidMount } from "@/hooks";
import MtExport from "../modals/MtExport";
import { useRequest } from "ahooks";
import OrderImport from "../modals/OrderImport";
import EntrustOrderUpload from "../modals/EntrustOrderUpload";
import XlOrderColumn from "@/components/Table/XlOrderColumn";
import { fetchDictTemplatePath } from "@/pages/BasicInfo/services";
import WarehouseEntryImport from "../modals/WarehouseEntryImport";
import WarehouseEntryConfirm from "../modals/WarehouseEntryConfirm";
import WarehouseEntryUpdate from "../modals/WarehouseEntryUpdate";
import OrderMakeUp from "../modals/OrderMakeUp";

const {Item} = Form;

const OrderList = () => {
  const [form] = Form.useForm();

  const {getDict} = useModel('dictModel');
  const countrys = getDict('country');
  const sports = getDict('sport');
  const dports = getDict('dport');
  const prdTypes = getDict('prdType');
  const deliveryMethods = getDict('deliveryMethod');

  // order status 
  const [orderStatus, setOrderStatus] = useState<string []>(['all']);
  const [tabNumObj, setTabNumObj] = useState<any>({});
  
  // mt export
  const {loading: mtExportLoading, runAsync: orderExportMtApi} = useRequest(orderExportMt, {manual: true});
  const [currentRow, setCurrentRow] = useState<orderTypes | null>(null);
  const [mtExportVisible, setMtExportVsible] = useState(false);
  
  // import order
  const {loading: importOrderLoading, runAsync: orderImportTracksApi} = useRequest(orderImportTracks, {manual: true});
  const [importVisible, setImportVisible] = useState(false);

  // upload entrust
  const {loading: uploadEntrustLoading, runAsync: orderImportEntrustApi} = useRequest(orderImportEntrust, {manual: true});
  const [entrustUploadVisible, setEntrustUploadVisible] = useState(false);
  
  // 
  const [warehouseImportVisible, setWarehouseImportVisible] = useState(false);
  const {loading: warehouseImportLoading, runAsync: warehouseImportApi} = useRequest(importReceiptData, {manual: true});

  // 
  const [temPath, setTemPath] = useState(null);

  const [selectedRowKeys, setSelectedRowKeys] = useState<string []>([]);
  const [selectedRows, setSelectedRows] = useState<orderTypes []>([]);
  const [dataSource, setDataSource] = useState([]);
  const [pagination, setPagination] = useState({
    total: 0,
    pageNum: 1,
    pageSize: 20
  });

  //
  const [makeUpVisible, setMakeUpVisible] = useState(false);
  //
  const [inWhVerifyVisible, setInWhVerifyVisible] = useState(false);
  const {loading: inWhVerifyLoading, runAsync: inWhVerifyApi} = useRequest(confirmOrderInWhVerifyData, {manual: true});
  const [inWhVerifyAddVisible, setInWhVerifyAddVisible] = useState(false);
  const {loading: inWhVerifyAddLoading, runAsync: inWhVerifyAddApi} = useRequest(orderUpdateReceiptOrder, {manual: true});

  const fetchTabNumApi = (params: any = {}) => {
    fetchOrderTabNum({
      ...params,
      orderCodes: params?.orderCodes?.replace(/，/g, ',').replace(/\n/g, ',').split(',').filter((v: string) => v.trim())?.map((v: string) => v?.trim()),
    }).then(
      res => {
        setTabNumObj(res || {});
      }
    )
  }

  const getParams = () => {
    const params = form.getFieldsValue();
    return {
      ...params,
      orderTimeBegin: params?.orderTime?.[0] ? params?.orderTime?.[0].format('YYYY-MM-DD 00:00:00') : undefined,
      orderTimeEnd: params?.orderTime?.[1] ? params?.orderTime?.[1].format('YYYY-MM-DD 23:59:59') : undefined,
      orderTime: undefined
    }
  }
  
  const search = async (params: any) => {
    const res = await fetchOrderList({
      ...params,
      orderCodes: params?.orderCodes?.replace(/，/g, ',').replace(/\n/g, ',').split(',').filter((v: string) => v.trim())?.map((v: string) => v?.trim()),
      nodes: !params?.nodes || !params?.nodes?.length || params?.nodes?.includes('all') ? undefined : params?.nodes
    });
    setDataSource(res?.data || []);
    setPagination({
      total: res?.total,
      pageNum: res?.pageNum,
      pageSize: res?.pageSize
    });
  }

  const refreshData = () => {
    const params = getParams();
    search({
      ...params,
      node: orderStatus,
      pageNum: 1,
      pageSize: 20
    });
  }

  // 导出唛头
  const mtExportProps = {
    title: '导出唛头',
    currentRow,
    visible: mtExportVisible,
    loading: mtExportLoading,
    onCancel: () => {
      setMtExportVsible(false);
      setCurrentRow(null);
    },
    onSubmit: async (params: any) => {
      const res = await orderExportMtApi(params);
      if (res?.code && res?.data) {
        mtExportProps.onCancel();
        downloadFile(res?.data);
      }
    }
  }
  // 导入订单
  const orderImportProps = {
    title: '导入订单',
    visible: importVisible,
    loading: importOrderLoading,
    onCancel: () => {
      setImportVisible(false);
    },
    onSubmit: async (params:any) => {
      const res = await orderImportTracksApi(params);
      if (res?.code === '0') {
        message.success('导入成功!');
        orderImportProps.onCancel();
        refreshData();
      }
    }
  }
   // 上传委托单
   const uploadEntrustProps = {
    title: '上传委托单',
    currentRow,
    visible: entrustUploadVisible,
    loading: uploadEntrustLoading,
    onCancel: () => {
      setEntrustUploadVisible(false);
      setCurrentRow(null);
    },
    onSubmit: async (params:any) => {
      const res = await orderImportEntrustApi(params);
      if (res?.code === '0') {
        message.success('上传成功!');
        uploadEntrustProps.onCancel();
        refreshData();
      }
    }
  }

  const rowSelection = {
    selectedRowKeys,
    onChange: (keys: string [], rows: orderTypes []) => {
      setSelectedRowKeys(keys);
      setSelectedRows(rows);
    },
  }
  const warehouseImportProps = {
    title: "导入订单入仓数据",
    visible: warehouseImportVisible,
    loading: warehouseImportLoading,
    onCancel: () => {
      setWarehouseImportVisible(false);
    },
    onSubmit: async (params: any) => {
      const res = await warehouseImportApi(params);
      if (res?.code === '0'){
        warehouseImportProps.onCancel();
        message.success("操作成功!");
        refreshData();
      }
    }
  }

  const makeUpProps = {
    visible: makeUpVisible,
    title: "轨迹打标",
    currentRow,
    onCancel: () => {
      setMakeUpVisible(false);
      setCurrentRow(null);
    },
    onSubmit: () => {
      makeUpProps.onCancel();
     
    }
  }

  const editProps = {
    title: "编辑入仓核实数据",
    visible: inWhVerifyVisible,
    currentRow,
    loading: inWhVerifyLoading,
    onCancel: () => {
      setInWhVerifyVisible(false);
      setCurrentRow(null);
    },
    onSubmit: async (params:any) => {
      const res = await inWhVerifyApi(params);
      if (res?.code === '0') {
        editProps.onCancel();
        refreshData();
      }
    }
  }

  const addProps = {
    title: "录入入仓数据",
    visible: inWhVerifyAddVisible,
    currentRow,
    loading: inWhVerifyAddLoading,
    onCancel: () => {
      setInWhVerifyAddVisible(false);
      setCurrentRow(null);
    },
    onSubmit: async (params:any) => {
      const res = await inWhVerifyAddApi(params);
      if (res?.code === '0') {
        addProps.onCancel();
        refreshData();
      }
    }
  }
  
  const handleBatchConfirmEntry = () => {
    if (!selectedRowKeys?.length) {
      message.warning("请选择需要确认的数据!");
      return ;
    }
    Modal.confirm({
      title: "温馨提示",
      content: `确认${selectedRows?.map((v: orderTypes) => v.orderCode)?.join("，")}已和客户核实 ？`,
      onOk: () => {
        confirmOrderInWhVerifyData({ids: selectedRowKeys}).then(
          res => {
            if (res?.code === '0') {
              message.success("操作成功!");
              refreshData();
              setSelectedRowKeys([]);
              setSelectedRows([]);
            }
          }
        );
      }
    });
  }
  // 创建订单
  const toCreateOrder = () => {
    history.push('/order-manage/order-create');
  }
  // status change
  const handleStatusChange = (val: string []) => {
    const params = getParams();
    setOrderStatus(val);
    search({
      ...params,
      nodes: val,
      pageNum: 1,
      pageSize: 20
    });
    fetchTabNumApi();
  }
  // 取消订单
  // const handleOrderCancel = (record: orderTypes) => {
  //   Modal.confirm({
  //     title: "温馨提示",
  //     content: "是否确定取消此订单?",
  //     onOk: () => {
  //       orderCancel({id: record?.id}).then(
  //         res => {
  //           if (res?.code === '0') {
  //             refreshData();
  //           }
  //         }
  //       )
  //     }
  //   });
  // }
  // 编辑订单
  const handleOrderEdit = (record: orderTypes) => {
    history.push(`/order-manage/order-create?orderId=${record?.id}`);
  }
  // 导出唛头
  const handleCodeExport = (record: orderTypes) => {
    setCurrentRow(record);
    setMtExportVsible(true);
  }
  const handleEntrustUpload = (record: orderTypes) => {
    setCurrentRow(record);
    setEntrustUploadVisible(true);
  }
  const handleWarehouseEntryExport = () => {
    setWarehouseImportVisible(true);
  }
  const handleWarehouseEntryBatchExport = () => {
    if (!selectedRowKeys?.length) {
      message.warning("请选择需要合并导出的数据!");
      return ;
    }
    history.push(`/order-manage/warehouse-entry-verify?ids=${selectedRowKeys.join(',')}`);
  }
  const handleWarehouseEntryDownload = (record: orderTypes) => {
    exportInWhDataSingle({id: record?.id}).then(
      res => {
        if (res) {
          downloadFile(res);
        }
      }
    )
  }
  const handleWarehouseEntryConfirm = (record: orderTypes) => {
    Modal.confirm({
      title: "温馨提示",
      content: "是否确认入仓核实?",
      onOk: () => {
        confirmOrderInWhVerifyData({ids: [record?.id]}).then(
          res => {
            if (res?.code === '0') {
              message.success("操作成功!");
              refreshData();
            }
          }
        );
      }
    });
  }
  
  const handleMakeUp = (record: orderTypes, makeUpFlag: string) => {
    setCurrentRow({...record, makeUpFlag});
    setMakeUpVisible(true);

  }
  const hanleEntryDataAdd = (record: orderTypes) => {
    setCurrentRow(record);
    setInWhVerifyAddVisible(true);
  }
  const hanleEntryDataEdit = (record: orderTypes) => {
    setCurrentRow(record);
    setInWhVerifyVisible(true);
  }

  const columns: ColumnsType<orderTypes> = [
    {
      title: '订单号',
      dataIndex: 'orderCode',
      fixed: 'left',
      width: 120,
      render: (_, record: orderTypes) => <XlOrderColumn record={record} />
    },
    {
      title: '订单状态',
      dataIndex: 'opStatusText',
      width: 150,
    },
    {
      title: '委托单',
      dataIndex: 'entrustFlag',
      width: 120,
      render: (_, record: orderTypes) => <span>{record?.entrustFlag === '1' ? '已上传' : '未上传'}</span>
    },
    {
      title: '业务时间',
      dataIndex: 'businessTime',
      width: 180,
    },
    {
      title: '所属销售',
      dataIndex: 'salesName',
      width: 120,
    },
    {
      title: '下单公司简称',
      dataIndex: 'customerName',
      ellipsis: true,
      width: 120,
    },
    {
      title: '下单手机号',
      dataIndex: 'mobile',
      ellipsis: true,
      width: 120,
    },
    {
      title: '产品名称',
      dataIndex: 'productName',
      ellipsis: true,
      width: 120,
    },
    {
      title: '国家',
      dataIndex: 'countryName',
      ellipsis: true,
      width: 120,
    },
    {
      title: '起始地',
      dataIndex: 'sportName',
      width: 120,
    },
    {
      title: '目的港',
      dataIndex: 'dportName',
      width: 120,
    },
    {
      title: '目的地',
      dataIndex: 'destCode',
      ellipsis: true,
      width: 120,
    },
    {
      title: '派送方式',
      dataIndex: 'deliveryMethod',
      width: 120,
    },
    {
      title: '委托件数',
      dataIndex: 'totalPieces',
      width: 120,
    },
    {
      title: '委托总体积/CBM',
      dataIndex: 'totalVol',
      width: 150,
    },
    {
      title: '委托总重量/KG',
      dataIndex: 'totalWeight',
      width: 150,
    },
    {
      title: '实际件数',
      dataIndex: 'inWhPieces',
      width: 120,
    },
    {
      title: '实际总体积/CBM',
      dataIndex: 'inWhVol',
      width: 150,
    },
    {
      title: '实际总重量/KG',
      dataIndex: 'inWhWeight',
      width: 150,
    },
    {
      title: '备注',
      dataIndex: 'remark',
      ellipsis: true,
      width: 150,
    },
    {
      title: '外部单号',
      dataIndex: 'exOrderCode',
      width: 150,
    },
    {
      title: '业务单号',
      dataIndex: 'bookingCode',
      width: 150,
    },
    {
      title: '操作',
      dataIndex: 'operations',
      width: 530,
      fixed: 'right',
      render: (_, record: any) => {
        const btnMaps: any = {
          edit: <Button type="link" key="edit" onClick={() => handleOrderEdit(record)}>编辑订单</Button>,
          // cancel: <Button type="link" key="cancel" onClick={() => handleOrderCancel(record)}>取消订单</Button>,
          uploadEntrustFile: <Button type="link" key="uploadEntrust" onClick={() => handleEntrustUpload(record)}>上传委托单</Button>,
          exportMt: <Button type="link" key="mtExport" onClick={() => handleCodeExport(record)}>唛头导出</Button>,
          exportInWhData: <Button type="link" key="下载入仓核实单" onClick={() => handleWarehouseEntryDownload(record)}>下载入仓核实单</Button>,
          confirmInWhVerifyData: <Button type="link" key="确认入仓核实单" onClick={() => handleWarehouseEntryConfirm(record)}>确认入仓核实单</Button>,
          markBookingCar: <Button type="link" key="标记约车" onClick={() => handleMakeUp(record, "markBookingCar")}>标记约车</Button>,
          markArriveDomesticWh:  <Button type="link" key="标记到仓" onClick={() => handleMakeUp(record, "markArriveDomesticWh")}>标记到仓</Button>,
          markDelivery: <Button type="link" key="标记派送" onClick={() => handleMakeUp(record, "markDelivery")}>标记派送</Button>,
          markSign: <Button type="link" key="标记签收" onClick={() => handleMakeUp(record, "markSign")}>标记签收</Button>,
          updateInWhDate: <Button type="link" key="录入入仓数据" onClick={() => hanleEntryDataAdd(record)}>录入入仓数据</Button>,
          updateOrderInWhVerifyData: <Button type="link" key="编辑入仓数据" onClick={() => hanleEntryDataEdit(record)}>编辑入仓核实数据</Button>,
        }
        return (
          <Space>
            {
              record?.operations?.map((v: string) => btnMaps?.[v])
            }
          </Space>
        );
      }
    },
  ];

  const composeOrderStatusMaps = useMemo(() => {
    return orderStatusMaps.map(v => ({
      ...v,
      label: tabNumObj?.[v?.num] > 0 ? `${v?.label} (${tabNumObj?.[v?.num]})` : v.label
    }))
  }, [JSON.stringify(tabNumObj), JSON.stringify(orderStatusMaps)]);

  const handleSearch = () => {
    const params = getParams();
    search({
      ...params,
      nodes: orderStatus,
      pageNum: 1,
      pageSize: 20
    });
    fetchTabNumApi(params);
  }
  const handleReset = () => {
    form.resetFields();
    search({
      nodes: orderStatus,
      pageNum: 1,
      pageSize: 20
    });
  }
  const handleImportOrder = () => {
    setImportVisible(true);
  }

  useComponentDidMount(() => {
    search({
      pageNum: 1,
      pageSize: 20
    });
    fetchTabNumApi();
    fetchDictTemplatePath({templateKey: "orderTrackTemplate"}).then(
      res => {
        setTemPath(res);
      }
    )
  })

  return (
    <>
      <Form form={form} layout="inline">
        <Item label="订单号" name="orderCodes" style={{marginBottom: 15}}>
          <Input.TextArea rows={1} allowClear onPressEnter={handleSearch} />
        </Item>
        <Item label="外部单号" name="exOrderCode" style={{marginBottom: 15}}>
          <Input allowClear />
        </Item>
        <Item label="国家" name="country" style={{marginBottom: 15}}>
          <XlSelect options={countrys} allowClear style={{width: 183}} />
        </Item>
        <Item label="起始地" name="sportCode" style={{marginBottom: 15}}>
          <XlSelect options={sports} allowClear style={{width: 183}} />
        </Item>
        <Item label="目的地" name="dportCode" style={{marginBottom: 15}}>
          <XlSelect options={dports} allowClear style={{width: 183}} />
        </Item>
        <Item label="产品" name="product" style={{marginBottom: 15}}>
          <XlSelect options={prdTypes} allowClear style={{width: 183}} />
        </Item>
        <Item label="下单公司" name="customerName" style={{marginBottom: 15}}>
          <Input allowClear />
        </Item>
        <Item label="派送方式" name="deliveryMethod" style={{marginBottom: 15}}>
          <XlSelect allowClear options={deliveryMethods} style={{width: 183}} />
        </Item>
        <Item label="时间" name="orderTime" style={{marginBottom: 15}}>
          <DatePicker.RangePicker />
        </Item>
        <Space style={{marginBottom: 20}}>
          <Button type="primary" onClick={handleSearch}>查询</Button>
          <Button type="default" onClick={handleReset}>重置</Button>
        </Space>
      </Form>
      <div style={{marginBottom: 10}}>
        <XlCheckBox.ButtonGroup totalNum={tabNumObj?.totalNum} hasAll value={orderStatus} onChange={(val: string []) => handleStatusChange(val)} options={composeOrderStatusMaps} />
      </div>
      <Space>
        <Button type="primary" key="新建订单" onClick={toCreateOrder}><PlusOutlined />新建订单</Button>
        {temPath && <Button type="primary" key="订单轨迹模板" onClick={() => downloadFile(temPath)}><ArrowDownOutlined />订单轨迹模板</Button>}
        <Button type="primary" key="导入订单轨迹" onClick={handleImportOrder}><PlusOutlined />导入订单轨迹</Button>
        <Button type="primary" key="导入仓数据" onClick={handleWarehouseEntryExport}><PlusOutlined />导入仓数据</Button>
        <Button type="primary" key="合并导出入仓核实单" onClick={handleWarehouseEntryBatchExport}><PlusOutlined />合并导出入仓核实单</Button>
        <Button type="primary" key="批量确认入仓核实单" onClick={handleBatchConfirmEntry}><PlusOutlined />批量确认入仓核实单</Button>
      </Space>
      <Table
        className="mt10"
        rowKey="id"
        bordered
        dataSource={dataSource}
        columns={columns}
        scroll={{x: calculateTableWidth(columns), y: 530}}
        rowSelection={rowSelection}
        pagination={{
          showTotal: (total: number) => `共 ${total} 条`,
          ...pagination,
          onChange: (pageNum, pageSize) => {
            const params = getParams();
            search({
              ...params,
              pageNum,
              pageSize
            });
          }
        }}
      />
      {mtExportVisible && <MtExport {...mtExportProps} />}
      {importVisible && <OrderImport {...orderImportProps} />}
      {entrustUploadVisible && <EntrustOrderUpload {...uploadEntrustProps} />}
      {warehouseImportVisible && <WarehouseEntryImport {...warehouseImportProps} />}
      {makeUpVisible && <OrderMakeUp {...makeUpProps} />}
      {inWhVerifyVisible && <WarehouseEntryConfirm {...editProps} />}
      {inWhVerifyAddVisible && <WarehouseEntryUpdate {...addProps} />}
    </>
  );
}
export default OrderList;